<template>
  <XenPageLayout
    title="消息详情"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
    :loading="loading"
    :error="hasError"
    @retry="loadNotificationDetail"
  >
    <!-- 内容区域 -->
    <view class="details-container">
      <!-- 详情内容 -->
      <view class="details-card">
        <view class="card-content">
          <!-- 消息头部信息 -->
          <view class="message-header">
            <view class="message-icon-container">
              <view class="message-icon">
                <!-- 根据消息类型显示不同图标 -->
                <i
                  v-if="notificationDetail.Category?.Icon"
                  :class="notificationDetail.Category.Icon"
                  style="font-size: 24px; color: #ffffff"
                ></i>
                <uni-icons
                  v-else
                  :type="getMessageIcon(notificationDetail.BusinessType) as any"
                  size="24"
                  color="#ffffff"
                ></uni-icons>
              </view>
              <!-- 优先级标识 -->
              <view
                v-if="
                  notificationDetail.Priority &&
                  notificationDetail.Priority !== '普通'
                "
                class="priority-badge"
                :class="getPriorityClass(notificationDetail.Priority)"
              >
                {{ notificationDetail.Priority }}
              </view>
            </view>
            <view class="message-title">
              {{ notificationDetail.Title || "无标题" }}
            </view>
          </view>

          <!-- 消息详情信息 -->
          <view class="message-details">
            <!-- 发送人信息 -->
            <view class="detail-item">
              <view class="detail-label">发送人</view>
              <view class="detail-value">{{
                notificationDetail.SenderName || "系统"
              }}</view>
            </view>

            <!-- 发送时间 -->
            <view class="detail-item">
              <view class="detail-label">发送时间</view>
              <view class="detail-value">{{
                formatDateTime(notificationDetail.SendTime)
              }}</view>
            </view>

            <!-- 阅读时间 -->
            <view class="detail-item" v-if="notificationDetail.ReadTime">
              <view class="detail-label">阅读时间</view>
              <view class="detail-value">{{
                formatDateTime(notificationDetail.ReadTime)
              }}</view>
            </view>

            <!-- 阅读状态 -->
            <view class="detail-item">
              <view class="detail-label">阅读状态</view>
              <view class="detail-value">
                <view
                  class="status-badge"
                  :class="getStatusClass(notificationDetail.Status)"
                >
                  {{ notificationDetail.Status }}
                </view>
              </view>
            </view>

            <!-- 业务类型 -->
            <view class="detail-item" v-if="notificationDetail.BusinessType">
              <view class="detail-label">业务类型</view>
              <view class="detail-value">{{
                notificationDetail.BusinessType
              }}</view>
            </view>

            <!-- 单据编号 -->
            <view class="detail-item" v-if="notificationDetail.BillCode">
              <view class="detail-label">单据编号</view>
              <view class="detail-value">
                <text>{{ notificationDetail.BillCode }}</text>
                <!-- 查看单据小按钮 -->
                <button
                  v-if="shouldShowViewButton"
                  class="view-bill-small-btn"
                  @click="handleViewBill"
                >
                  <text class="small-btn-text">查看单据</text>
                </button>
              </view>
            </view>
          </view>

          <!-- 消息内容 -->
          <view class="message-content">
            <view class="content-header">
              <view class="content-title">消息内容</view>
            </view>
            <view class="content-body">
              <text class="content-text">{{
                notificationDetail.Content || "无内容"
              }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";

import SysNotificationApi from "./api/index";
import type { ISysNotificationView } from "./api/interface";

// 创建API实例
const api = SysNotificationApi();

// 页面状态
const notificationId = ref<string>("");
const loading = ref(false);
const hasError = ref(false);

// 消息详情数据
const notificationDetail = ref<ISysNotificationView>(
  {} as ISysNotificationView,
);

// 根据业务类型获取消息图标
const getMessageIcon = (businessType: string | null): string => {
  if (!businessType) return "chatbubble";

  // 根据业务类型映射图标
  const iconMap: Record<string, string> = {
    系统通知: "gear",
    工作流: "paperplane",
    审批: "checkmarkempty",
    提醒: "alarm",
    公告: "megaphone",
    消息: "chatbubble",
    邮件: "mail",
    任务: "list",
    会议: "calendar",
    文档: "document",
  };

  // 查找匹配的图标
  for (const [key, icon] of Object.entries(iconMap)) {
    if (businessType.includes(key)) {
      return icon;
    }
  }

  return "chatbubble"; // 默认图标
};

// 获取优先级样式类
const getPriorityClass = (priority: string): string => {
  const classMap: Record<string, string> = {
    低: "priority-low",
    普通: "priority-normal",
    高: "priority-high",
    紧急: "priority-urgent",
  };
  return classMap[priority] || "priority-normal";
};

// 获取状态样式类
const getStatusClass = (status: string): string => {
  return status === "已读" ? "status-read" : "status-unread";
};

// 格式化日期时间
const formatDateTime = (dateTime: any): string => {
  if (!dateTime) return "";

  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 判断是否显示查看单据按钮
const shouldShowViewButton = computed(() => {
  return !!(
    notificationDetail.value.Route?.MobileRoute &&
    notificationDetail.value.BusinessId
  );
});

// 查看单据 - 参考待办中心的 handleView 函数实现
const handleViewBill = () => {
  const notification = notificationDetail.value;

  // 检查 MobileRoute 字段
  if (
    notification.Route?.MobileRoute &&
    notification.Route.MobileRoute.trim() !== ""
  ) {
    // 构建跳转参数
    const params: Record<string, string> = {
      id: notification.BusinessId || "",
    };

    // 构建查询字符串
    const queryString = Object.keys(params)
      .map((key) => `${key}=${encodeURIComponent(params[key])}`)
      .join("&");

    // 构建完整的跳转路径
    const fullPath = `${notification.Route.MobileRoute}?${queryString}`;

    // 执行路由跳转
    uni.navigateTo({
      url: fullPath,
      success: () => {
        console.log(`跳转成功: ${fullPath}`);
      },
      fail: (error) => {
        console.error("跳转失败:", error);
        uni.showToast({
          title: "页面跳转失败",
          icon: "none",
          duration: 2000,
        });
      },
    });
  } else {
    // MobileRoute 为空，显示提示信息
    uni.showToast({
      title: "请到PC端进行审核",
      icon: "none",
      duration: 2000,
    });
  }
};

// 加载消息详情
const loadNotificationDetail = async () => {
  if (!notificationId.value) {
    hasError.value = true;
    return;
  }

  loading.value = true;
  hasError.value = false;

  try {
    const response = await api.get(notificationId.value);

    if (response && response.Entity) {
      notificationDetail.value = response.Entity;

      // 如果消息未读，标记为已读
      if (notificationDetail.value.Status === "未读") {
        try {
          await api.edit({
            Entity: {
              ...notificationDetail.value,
              Status: "已读",
              ReadTime: new Date(),
            },
          });

          // 更新本地数据
          notificationDetail.value.Status = "已读";
          notificationDetail.value.ReadTime = new Date();
        } catch (error) {
          console.error("标记已读失败:", error);
        }
      }
    } else {
      hasError.value = true;
      uni.showToast({
        title: "获取消息详情失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取消息详情异常:", error);
    hasError.value = true;
    uni.showToast({
      title: "获取消息详情异常",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 获取分享标题
const getShareTitle = () => {
  if (notificationDetail.value?.Title) {
    return `系统通知${notificationDetail.value.Title}`;
  }
  return "系统通知详情";
};

// 获取分享路径
const getSharePath = () => {
  if (notificationId.value) {
    return `/subpkg-sysnotification/details?id=${notificationId.value}`;
  }
  return "/subpkg-sysnotification/index";
};

// 页面加载时获取路由参数
onLoad((options) => {
  if (options?.id) {
    notificationId.value = options.id;
  } else {
    uni.showToast({
      title: "缺少消息ID参数",
      icon: "none",
    });
    hasError.value = true;
  }

  // 设置微信小程序分享功能
  // #ifdef MP-WEIXIN
  onShareAppMessage(() => {
    return {
      title: getShareTitle(),
      path: getSharePath(),
      imageUrl: "", // 可以设置分享图片
    };
  });
  // #endif
});

// 页面挂载后加载数据
onMounted(() => {
  if (notificationId.value) {
    loadNotificationDetail();
  }
});
</script>

<style lang="scss" scoped>
.details-container {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  min-height: calc(100vh - 80px);

  .details-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    min-height: 80vh;
    overflow: hidden;

    .card-content {
      padding: 24px;
    }
  }
}

/* 消息头部样式 */
.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;

  .message-icon-container {
    position: relative;
    margin-right: 16px;
    flex-shrink: 0;

    .message-icon {
      width: 56px;
      height: 56px;
      border-radius: 28px;
      background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .priority-badge {
      position: absolute;
      top: -4px;
      right: -4px;
      padding: 2px 6px;
      border-radius: 8px;
      font-size: 10px;
      font-weight: 600;
      color: #ffffff;

      &.priority-low {
        background: #10b981;
      }

      &.priority-high {
        background: #f59e0b;
      }

      &.priority-urgent {
        background: #ef4444;
      }
    }
  }

  .message-title {
    word-break: break-all;
    flex: 1;
    font-size: 20px;
    font-weight: 600;
    color: #1a1a1a;
    line-height: 1.4;
    margin-top: 8px;
  }
}

/* 消息详情样式 */
.message-details {
  margin-bottom: 24px;

  .detail-item {
    display: flex;
    align-items: center;
    padding: 2px 0;
    border-bottom: 1px solid #f8f9fa;

    &:last-child {
      border-bottom: none;
    }

    .detail-label {
      width: 80px;
      font-size: 14px;
      color: #666;
      flex-shrink: 0;
    }

    .detail-value {
      flex: 1;
      font-size: 14px;
      color: #333;
      display: flex;
      align-items: center;
      gap: 8px;

      .status-badge {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;

        &.status-read {
          background: #dcfce7;
          color: #16a34a;
        }

        &.status-unread {
          background: #fef3c7;
          color: #d97706;
        }
      }

      .view-bill-small-btn {
        display: flex;
        align-items: center;
        gap: 4px;
        padding: 0px 10px;
        background: linear-gradient(135deg, #7881de 0%, #9973f8 100%);
        border: none;
        border-radius: 20px;
        font-size: 12px;
        transition: all 0.2s ease;
        margin-left: auto;
        flex-shrink: 0;
        box-shadow: 0 2px 8px rgba(120, 129, 222, 0.25);

        &:active {
          opacity: 0.8;
          transform: scale(0.96);
          box-shadow: 0 1px 4px rgba(120, 129, 222, 0.3);
        }

        &:hover {
          box-shadow: 0 3px 12px rgba(120, 129, 222, 0.35);
        }

        .small-btn-text {
          font-size: 12px;
          color: #ffffff;
          font-weight: 500;
        }
      }
    }
  }
}

/* 消息内容样式 */
.message-content {
  .content-header {
    margin-bottom: 16px;

    .content-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .content-body {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 16px;

    .content-text {
      font-size: 15px;
      line-height: 1.6;
      color: #333;
      white-space: pre-wrap;
      word-break: break-word;
    }
  }
}
</style>
